package textapp.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import textapp.business.GroupService;
import textapp.business.RegisterService;
import textapp.connector.MessageCode;
import textapp.connector.ServerConnectorMessage;
import textapp.dao.model.Group;
import textapp.dao.model.GroupUser;
import textapp.dao.model.User;

/**
 * Servlet implementation class CreateGroupJsonServlet
 */
public class CreateGroupJsonServlet extends GenericJsonServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateGroupJsonServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	@Override
	protected Object executeRequestJson(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		try {
			int ownerId = Integer.parseInt(request.getParameter("owner"));
			String name = request.getParameter("name");
			if (name == null) {
				throw new Exception();
			}
			int type = Integer.parseInt(request.getParameter("type"));
			String idStr = request.getParameter("ids");
			String[] idArr = idStr.split(";");
			ArrayList<Integer> idList = new ArrayList<Integer>();
			for (String i: idArr) {
				if (i.startsWith("P")) {
					i = i.substring(1);
					RegisterService reg = new RegisterService();
					User newUser = reg.registerNonMemDevice(i, i);
					idList.add(newUser.getId());
				} else {
					idList.add(Integer.parseInt(i));
				}
				
			}
			if (idList.size() == 0) {
				throw new Exception();
			}
			Group group = new GroupService().createGroup(ownerId, name, type, idList);
			
			// Prevent circular error from Gson
			Group newGroup = new Group();
			newGroup.setId(group.getId());
			newGroup.setName(group.getName());
			newGroup.setOwner(group.getOwner());
			newGroup.setType(group.getType());
			newGroup.setGroupUsers(group.getGroupUsers());
			for (GroupUser gu : newGroup.getGroupUsers()) {
				gu.getGroup().setGroupUsers(null);
			}
			
			return new ServerConnectorMessage(MessageCode.SUCCESS, newGroup);
			
		} catch(Throwable t) {
			return new ServerConnectorMessage(MessageCode.FAIL);
		}
		

	}

    
	
}
